package com.heatup.apt.management.service.company.impl;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.plugins.Page;
import com.heatup.apt.common.dao.CompanyInfoMapper;
import com.heatup.apt.management.service.company.CompanyInfoService;
import com.heatup.apt.management.util.ExcelDocumentor;
import com.heatup.apt.model.company.CompanyInfo;
import com.heatup.apt.model.order.OrderCompanyDetailInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * CompanyInfo 表数据服务层接口实现类
 */
@Service
public class CompanyInfoServiceImpl extends SuperServiceImpl<CompanyInfoMapper, CompanyInfo> implements CompanyInfoService {

    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    /**
     * 分页查询企业列表
     *
     * @param companyInfoPage 分页
     * @param companyInfo     查询参数
     * @return
     */
    @Override
    public Page<CompanyInfo> selectCompanyList(Page<CompanyInfo> companyInfoPage, CompanyInfo companyInfo) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("name", companyInfo.getName());
        companyInfoPage.setRecords(companyInfoMapper.selectCompanyList(companyInfoPage, queryMap));
        return companyInfoPage;
    }

    /**
     * 查询是否存在相同的公司名称
     *
     * @param companyInfo 企业
     * @return true 存在/false 不存在
     */
    @Override
    public boolean checkByName(CompanyInfo companyInfo) {
        CompanyInfo companyInfoQuery = new CompanyInfo();
        companyInfoQuery.setName(companyInfo.getName());

        CompanyInfo companyInfoDB = companyInfoMapper.selectOne(companyInfoQuery);
        return companyInfoDB != null;
    }

    /**
     * 保存企业
     *
     * @param companyInfo 企业
     * @param userId      用户ID
     * @return
     */
    @Override
    public boolean saveCompany(CompanyInfo companyInfo, Integer userId) {
        if (companyInfo == null)
            return false;
        if (companyInfo.getIsMonthlyLimit() == 1) {
            companyInfo.setMonthlyLimit(new BigDecimal(0));
        }
        if (companyInfo.getIsMonthlyTotalLimit() == 1) {
            companyInfo.setMonthlyTotalLimit(new BigDecimal(0));
        }
        if (companyInfo.getIsBuyTypeLimit() == 1) {
            companyInfo.setLimitTeamCourse(1);
            companyInfo.setLimitSecretCourse(1);
            companyInfo.setLimitCampCourse(1);
            companyInfo.setLimitSelfCourse(1);
            companyInfo.setLimitVip(1);
            companyInfo.setLimitValuedCard(1);
        } else {
            if (companyInfo.getLimitTeamCourse() == null) {
                companyInfo.setLimitTeamCourse(0);
            }
            if (companyInfo.getLimitSecretCourse() == null) {
                companyInfo.setLimitSecretCourse(0);
            }
            if (companyInfo.getLimitCampCourse() == null) {
                companyInfo.setLimitCampCourse(0);
            }
            if (companyInfo.getLimitSelfCourse() == null) {
                companyInfo.setLimitSelfCourse(0);
            }
            if (companyInfo.getLimitVip() == null) {
                companyInfo.setLimitVip(0);
            }
            if (companyInfo.getLimitValuedCard() == null) {
                companyInfo.setLimitValuedCard(0);
            }
        }
        //是否限制可使用门店
        if (companyInfo.getIsStoreListLimit() == 0) {
            //替换","为"#"
            companyInfo.setStoreListLimit(companyInfo.getStoreListLimit().replaceAll(",","#"));
        }
        if (companyInfo.getVipCheckType() == 0) {
            //按会员价格
            //是否限制以会员价使用门店
            if (companyInfo.getVipCheckStoreLimit() == 0) {
                //替换","为"#"
                companyInfo.setVipCheckStoreList(companyInfo.getVipCheckStoreList().replaceAll(",","#"));
            }
            //是否限制以会员价结算的课程类型
            if (companyInfo.getVipCheckCourseTypeLimit() == 1) {
                //不限购买类型 全部设置为允许
                companyInfo.setVipCheckCourseTypeTeam(1);
                companyInfo.setVipCheckCourseTypePrivate(1);
                companyInfo.setVipCheckCourseTypeCamp(1);
                companyInfo.setVipCheckCourseTypeSelf(1);
            } else {
                if (companyInfo.getVipCheckCourseTypeTeam() == null) {
                    companyInfo.setVipCheckCourseTypeTeam(0);
                }
                if (companyInfo.getVipCheckCourseTypePrivate() == null) {
                    companyInfo.setVipCheckCourseTypePrivate(0);
                }
                if (companyInfo.getVipCheckCourseTypeCamp() == null) {
                    companyInfo.setVipCheckCourseTypeCamp(0);
                }
                if (companyInfo.getVipCheckCourseTypeSelf() == null) {
                    companyInfo.setVipCheckCourseTypeSelf(0);
                }
            }
        }
        if (companyInfo.getId() == null) {
            companyInfo.setStatus(0);
            companyInfo.setCreatedBy(userId);
            companyInfo.setCreatedTime(new Date());
            return companyInfoMapper.insertSelective(companyInfo) > 0;
        } else {
            companyInfo.setUpdatedBy(userId);
            companyInfo.setUpdatedTime(new Date());
            return companyInfoMapper.updateSelectiveById(companyInfo) > 0;
        }

    }


    /**
     * 查询企业余额
     *
     * @param companyId 企业
     * @return 企业余额
     */
    @Override
    public BigDecimal selectCompanyAmountById(Long companyId) {
        return companyInfoMapper.selectCompanyAmountById(companyId);
    }

    /**
     * 下载企业指定年月订单流水
     *
     * @param orderCompanyDetailInfo 企业
     */
    @Override
    public String queryOrderDetailList(OrderCompanyDetailInfo orderCompanyDetailInfo) {
        List<OrderCompanyDetailInfo> list = companyInfoMapper.queryOrderDetailList(orderCompanyDetailInfo);
        return downloadCompanyOrderDetail(list, orderCompanyDetailInfo);
    }


    /**
     * 生成待下载的文件
     *
     * @param list                   企业指定年月订单流水列表
     * @param orderCompanyDetailInfo 企业年月
     * @return 自动生成文件名
     */
    private String downloadCompanyOrderDetail(List<OrderCompanyDetailInfo> list, OrderCompanyDetailInfo orderCompanyDetailInfo) {

        if (list == null || list.size() == 0 || orderCompanyDetailInfo.getYear() == null || orderCompanyDetailInfo.getMonth() == null) {
            return null;
        }

        String userHomePath = System.getProperty("user.home") + File.separator + "temp";
        String month = orderCompanyDetailInfo.getMonth().toString().length() == 1 ? "0" + orderCompanyDetailInfo.getMonth() : orderCompanyDetailInfo.getMonth() + "";
        String fileName = list.get(0).getCompanyName() + " " + orderCompanyDetailInfo.getYear() + " " + month + ".xls";

        //创建目录
        File dirFile = new File(userHomePath);
        if (dirFile.exists()) {
            if (!dirFile.isDirectory()) {
                dirFile.mkdir();
            }
        } else {
            dirFile.mkdir();
        }

        Map<String, String> columns = new LinkedHashMap<>();
        columns.put("companyId", "企业ID");
        columns.put("companyName", "企业名称");
        columns.put("userId", "用户ID");
        columns.put("orderNumber", "订单号");
        columns.put("title", "购买类型");
        columns.put("payTime", "支付时间");
        columns.put("name", "消费员工");
        columns.put("mobile", "员工手机");
        columns.put("storeName", "门店");
        columns.put("price", "费用");
        columns.put("amount", "实付");
        columns.put("coupon", "优惠券");
        columns.put("orderStatus", "状态");
        ExcelDocumentor documentor = new ExcelDocumentor();
        documentor.exportTable(list, columns, new File(userHomePath + File.separator + fileName));
        return fileName;
    }
}